//
//  CGSearchViewController.m
//  SchoolClient
//
//  Created by mac on 15/11/5.
//  Copyright © 2015年 mac. All rights reserved.
//

#import "CGSearchViewController.h"
#import "CGInfoCompany.h"

@interface CGSearchViewController ()

@property(nonatomic,strong)CGSearchBar *searchBar;
@property(nonatomic,strong)NSArray *products;                    //所有产品
@property(nonatomic,strong)NSString *model;
@property(nonatomic,strong)NSMutableArray *companyFrames;         //所有企业产品
@property(nonatomic,strong)NSMutableArray *schoolFrames;          //所有学校产品


@property(nonatomic,strong)CGInfoCompany *company;
@property(nonatomic,strong)CGInfoSchool *school;

@end

@implementation CGSearchViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [Tools getColor:@"ebebeb"];
    
    [self initNavigationBarButton];
    [self initTableView];
    
    //[self searchWithKeyword:@"创冠"];
    
    //使cell的线条充满
    if ([self.tableView respondsToSelector:@selector(setSeparatorInset:)]) {
        
        [self.tableView setSeparatorInset:UIEdgeInsetsZero];
        
    }
    if ([self.tableView respondsToSelector:@selector(setLayoutMargins:)]) {
        
        [self.tableView setLayoutMargins:UIEdgeInsetsZero];
        
    }

}

-(NSMutableArray *)companyFrames{
    if (!_companyFrames) {
        _companyFrames = [NSMutableArray array];
    }
    return _companyFrames;
}

-(NSMutableArray *)schoolFrames{
    if (!_schoolFrames) {
        _schoolFrames = [NSMutableArray array];
    }
    return _schoolFrames;
}


#pragma mark 添加导航按钮
-(void)initNavigationBarButton{
    
    //1.设置中间导航视图为searchBar
    self.searchBar = [[CGSearchBar alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH - 80, 35)];
    self.searchBar.placeholder = @"查找公司或职位";
    self.searchBar.returnKeyType = UIReturnKeySearch;
    self.searchBar.delegate = self;
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:self.searchBar];
    [self.searchBar becomeFirstResponder];
    
    //2.右导航按钮
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"取消" style:UIBarButtonItemStylePlain target:self action:@selector(comeBack)];
    
    //监听textField内容修改事件
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(TextDidChange:) name:UITextFieldTextDidChangeNotification object:self.searchBar];
    
}



#pragma mark 发送请求获取产品
-(void)searchWithKeyword:(NSString *)keyword{
    
    //2.发送登录请求
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@"page"] = @"0";
    parameters[@"pageSize"] = [NSString stringWithFormat:@"%d",(int)SCREEN_HEIGHT/100];
    parameters[@"search"] = keyword;
    
    ZYHRequest *request = [ZYHRequest new];
    [request postAsyncEncryptRequest:@"/main/getSearchHomeData.app" parameters:parameters success:^(id responseData) {
        
        NSLog(@"搜索请求发送成功");
        NSDictionary *jsonDic =  [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableContainers error:NULL];
        NSString *value = jsonDic[@"data"];
        NSData *valueData = [value dataUsingEncoding:NSUTF8StringEncoding];
        self.products = [CGInfo objectArrayWithJSONData:valueData];
        [self.tableView reloadData];
        NSLog(@"result:%@",value);
        
    } failure:^(NSError *error) {
        
        [Tools alertWithTitle:@"温馨提示" andMessage:@"网络超时,请稍后再试"];
      
    }];
}


#pragma mark 单击取消退出搜索
-(void)comeBack{

    [self.navigationController popViewControllerAnimated:NO];
}


#pragma mark 输入框事件
//textField内容修改触发事件
-(void)TextDidChange:(NSNotification *)notice{
    
    CGSearchBar *textField = notice.object;
    [self searchWithKeyword:textField.text];
    
}

//回车退出键盘
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    
    [self.searchBar resignFirstResponder];
    return YES;
}

#pragma mark overide 表格的代理方法实现
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return self.products.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    CGInfo *searchInfo = self.products[indexPath.row];
    
    if (!searchInfo.type) {
        
        CGCompanyJobCell *cell = [tableView dequeueReusableCellWithIdentifier:@"company"];
        if (cell == nil) {
            cell = [[CGCompanyJobCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"company"];
        }
        //模型转视图模型
        CGInfoCompany *company = self.products[indexPath.row];
        CGInfoCompanyFrame *companyFrame = [CGInfoCompanyFrame new];
        companyFrame.product = company;
        cell.productFrame = companyFrame;
        
        return cell;
        
    }else{
        
        CGSChoolJobCell *cell = [tableView dequeueReusableCellWithIdentifier:@"school"];
        if (cell == nil) {
            cell = [[CGSChoolJobCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"school"];
        }
        
        //模型转视图模型
        CGInfoSchool *school = self.products[indexPath.row];
        CGInfoSchoolFrame *schoolFrame = [CGInfoSchoolFrame new];
        schoolFrame.product = school;
        cell.productFrame = schoolFrame;

        return cell;
    }
}

//设置单元格高度
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    CGInfo *searchInfo = self.products[indexPath.row];
    
    if (!searchInfo.type) {
        
        //模型转视图模型
        CGInfoCompany *company = self.products[indexPath.row];
        CGInfoCompanyFrame *companyFrame = [CGInfoCompanyFrame new];
        companyFrame.product = company;

        return companyFrame.cellHeight;
        
    }else{
        
        //模型转视图模型
        CGInfoSchool *school = self.products[indexPath.row];
        CGInfoSchoolFrame *schoolFrame = [CGInfoSchoolFrame new];
        schoolFrame.product = school;
        
        return schoolFrame.cellHeight;
    }
    
}


//使cell的线条充满
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath

{
    
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
        
        [cell setSeparatorInset:UIEdgeInsetsZero];
        
    }
    
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        
        [cell setLayoutMargins:UIEdgeInsetsZero];
        
    }
}

#pragma mark 选中单元格跳转到详情页
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    CGInfo *searchInfo = self.products[indexPath.row];
    
    NSString *product_id = searchInfo.info_id;
    
    if (!searchInfo.type) {  //企业信息
        
        [self fetchCompanyProWithProID:product_id];
        
    }else{    //学校信息
        
        [self fetchSchoolProWithProID:product_id];
    }
    
    
    
}

#pragma mark 发送请求获取企业招聘详情
-(void)fetchCompanyProWithProID:(NSString *)product_id{
    
    //2.发送登录请求
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@"userId"] = [CGAccountDefault shareAccount].user_id;
    parameters[@"id"] = product_id;
    ZYHRequest *request = [ZYHRequest new];
    [request postAsyncEncryptRequest:@"/company/showInfo.app" parameters:parameters success:^(id responseData) {
        
        NSString *result = [[NSString alloc]initWithData:responseData encoding:NSUTF8StringEncoding];
        NSLog(@"result:%@",result);
        
        //去除前面字符串
        if ([result rangeOfString:@"true"].location != NSNotFound) {
            
            NSMutableString *mstr = [NSMutableString stringWithString:result];
            NSRange range = NSMakeRange(0, 7);
            [mstr deleteCharactersInRange:range];
            result = mstr;
            
        }else if ([result rangeOfString:@"false"].location != NSNotFound){
            
            NSMutableString *mstr = [NSMutableString stringWithString:result];
            NSRange range = NSMakeRange(0, 8);
            [mstr deleteCharactersInRange:range];
            result = mstr;
            
        }else{
            
            [Tools alertWithTitle:@"温馨提示" andMessage:@"网络超时,请稍后再试"];
            return ;
        }
        
        //json转对象
        NSData *valueData = [result dataUsingEncoding:NSUTF8StringEncoding];
        CGInfoCompany *company = [CGInfoCompany objectWithJSONData:valueData];
        
        CGCompanyJobDetailViewController *companyDetailVC = [CGCompanyJobDetailViewController new];
        companyDetailVC.myCompanyInfo = company;
        [self.navigationController pushViewController:companyDetailVC animated:YES];
        
        
    } failure:^(NSError *error) {
        
        [Tools alertWithTitle:@"温馨提示" andMessage:@"网络超时,请稍后再试"];
        
    }];
}

#pragma mark 发送请求获取学校招聘详情
-(void)fetchSchoolProWithProID:(NSString *)product_id{
    
    //2.发送登录请求
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@"userId"] = [CGAccountDefault shareAccount].user_id;
    parameters[@"id"] = product_id;
    ZYHRequest *request = [ZYHRequest new];
    [request postAsyncEncryptRequest:@"/school/showInfo.app" parameters:parameters success:^(id responseData) {
        
        NSString *result = [[NSString alloc]initWithData:responseData encoding:NSUTF8StringEncoding];
        NSLog(@"result:%@",result);
        
        //去除前面字符串
        if ([result rangeOfString:@"true"].location != NSNotFound) {
            
            NSMutableString *mstr = [NSMutableString stringWithString:result];
            NSRange range = NSMakeRange(0, 7);
            [mstr deleteCharactersInRange:range];
            result = mstr;
            
        }else if ([result rangeOfString:@"false"].location != NSNotFound){
            
            NSMutableString *mstr = [NSMutableString stringWithString:result];
            NSRange range = NSMakeRange(0, 8);
            [mstr deleteCharactersInRange:range];
            result = mstr;
            
        }else{
            
            [Tools alertWithTitle:@"温馨提示" andMessage:@"网络超时,请稍后再试"];
            return ;
        }
        
        //json转对象
        NSData *valueData = [result dataUsingEncoding:NSUTF8StringEncoding];
        CGInfoSchool *school = [CGInfoSchool objectWithJSONData:valueData];
        //跳转
        CGSchoolJobDetailViewController *schoolDetailVC = [CGSchoolJobDetailViewController new];
        schoolDetailVC.mySchoolInfo = school;
        [self.navigationController pushViewController:schoolDetailVC animated:YES];
        
    } failure:^(NSError *error) {
        
        [Tools alertWithTitle:@"温馨提示" andMessage:@"网络超时,请稍后再试"];
        
    }];
}

@end
